package com.chen.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.common.Result;
import com.chen.mapper.RoleMapper;
import com.chen.mapper.UserMapper;
import com.chen.pojo.Role;
import com.chen.pojo.User;
import com.chen.pojo.UserRole;
import com.chen.pojo.bean.UserInfo;
import com.chen.service.Impl.UserServiceImpl;
import com.chen.utils.Md5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import static com.chen.utils.TokenUtils.getUser;

@SuppressWarnings("all")
@RestController
@RequestMapping("/user")
@Api(value = "UserController", tags = "用户操作")
public class UserController {
    @Resource
    private UserMapper userMapper;

    @Resource
    RoleMapper roleMapper;
    @Resource
    private UserServiceImpl userService;


    @ApiOperation("所有用户")
    @GetMapping("/all")
    public Result<?> userAll() {

        return Result.success(userMapper.selectList(null));
    }

    //审核页面
    @PutMapping("/agree/{id}")
    @ApiOperation("审核")
    public Result<?> agree(User user) {
        user.setStatus(1);
        userService.updateById(user);
        return Result.success(user);
    }


    //删除  从路径中获取值
    @DeleteMapping("/{id}")
    @ApiOperation("删除")
    public Result<?> delete(@PathVariable Long id) {
        return Result.success(userService.removeById(id));
    }


    //更新    接收前端传递给后端的json字符串中的数据
    @PutMapping("/updateUser")
    @ApiOperation("更新")
    public Result<?> updateUser(@RequestBody User user) {

        return Result.success(userService.updateById(user));
    }

    //    新增
    @PostMapping("/save")
    @ApiOperation(value = "新增")
    public Result<?> save(@RequestBody User user) {
        if (user.getPassword() == null) {
            user.setPassword(Md5.MD5("123456"));

        }
        user.setStatus(1);
        userService.save(user);
        return Result.success();
    }


    /* 分页查询  接受参数  当前页   每页的个数  根据什么查询
   如果默认参数不填会报400错误*/
    @RequestMapping("selectPage")
    @ApiOperation(value = "分页")
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search,
                              @RequestParam(defaultValue = "1") int status

    ) {
        /*模糊查询 根据昵称*/
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        wrapper.eq(User::getStatus, status);
        // 判断nick不为空时进行查询
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(User::getNick, search);
        }

        return Result.success(userService.pageMaps(new Page<>(pageNum, pageSize), wrapper));
    }


    //更新
    @PutMapping("/changeRole")
    @ApiOperation("更新权限菜单")
    public Result<?> changeRole(@RequestBody User user) {
        // 先根据角色id删除所有的角色跟权限的绑定关系
        roleMapper.deleteRoleByUserId(user.getId());
        // 再新增 新的绑定关系
        for (Integer roleId : user.getRoles()) {
            roleMapper.insertUserRole(user.getId(), roleId);
        }

        // 获取当前登录用户的角色id列表
        UserInfo currentUser = new UserInfo();
        // 如果当前登录用户的角色列表包含需要修改的角色id，那么就重新登录
        if (user.getId().equals(currentUser.getId())) {
            return Result.success(true);
        }
//        如果不包含，则返回false，不需要重新登录。
        return Result.success(false);
    }


    @GetMapping("/selectBook")
    @ApiOperation("多表查询")
    public Result<?> findPages(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize,
                               @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(User::getUsername, search);
        }

        Page<User> userPage = userMapper.findPages(new Page<>(pageNum, pageSize), search);
        for (User record : userPage.getRecords()) {
            List<UserRole> roles = roleMapper.getByUserRoleUserId(record.getId());
            List<Integer> roleIds = roles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
            record.setRoles(roleIds);
        }
        return Result.success(userPage);
    }

    /**
     * Excel导出
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = CollUtil.newArrayList();
        List<User> userList = userMapper.selectList(null);
        for (User user : userList) {
            Map<String, Object> row = new LinkedHashMap<>();
            row.put("用户名", user.getUsername());
            row.put("昵称", user.getNick());
            row.put("年龄", user.getAge());
            row.put("性别", user.getSex());
            row.put("地址", user.getAddress());
            row.put("注册时间", user.getRegtime());
            list.add(row);
        }


        // 2. 写excel
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(System.out);
    }

    /**
     * Excel导入
     * 导入的模板可以使用 Excel导出的文件
     *
     * @param file Excel
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    public Result<?> upload(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        List<List<Object>> lists = ExcelUtil.getReader(inputStream).read(1);
        List<User> saveList = new ArrayList<>();
        for (List<Object> row : lists) {
            User user = new User();
            user.setUsername(row.get(0).toString());
            user.setNick(row.get(1).toString());
            user.setAge(Integer.valueOf(row.get(2).toString()));
            user.setSex(row.get(3).toString());
            user.setAddress(row.get(4).toString());

            saveList.add(user);
        }
        for (User user : saveList) {
            userMapper.insert(user);
        }
        return Result.success();
    }

}
